﻿/* Browser Version */
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = userAgent.indexOf('opera') != -1 && opera.version(); // Opera
var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);   // Firefox
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);   // IE
var is_mac = userAgent.indexOf('mac') != -1;    // 是否为 Mac 操作系统

/* window */
function $$(id_obj) { // document.getElementById 的简写

    return typeof (id_obj) == "string" ? document.getElementById(id_obj) : id_obj;
};

/* Cookie Helper */
var CookieHelper = {
    get: function (name) {
        var cookie_start = document.cookie.indexOf(name);
        var cookie_end = document.cookie.indexOf(";", cookie_start);
        return cookie_start == -1 ? null : unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length)));
    },
    set: function (name, value, milliseconds, path, domain, secure) {
        var expires = new Date();
        if (typeof (milliseconds) == 'undefined') milliseconds = 31536000000;   // 默认为 1 年有效期
        if (!milliseconds || milliseconds <= 0) {   // 若 milliseconds 参数的值为 null 或者小于 0，则不设置有效期
            expires = null;
        } else {
            expires.setTime(expires.getTime() + milliseconds);
        }
        document.cookie = escape(name) + '=' + escape(value)
		    + (expires ? '; expires=' + expires.toGMTString() : '')
		    + '; path=' + (path || '/')
		    + (domain ? '; domain=' + domain : '')
		    + (secure ? '; secure' : '');
    }
};

/* window.open 的增强版 */
window.openEx = function () {
    var oNewWindow = null;
    var aryArgs = new Array();
    for (var i = 0, len = arguments.length; i < len; i++) { aryArgs.push("arguments[" + i + "]"); }
    if (aryArgs.length > 0) {
        eval("oNewWindow=window.showModalDialog(" + aryArgs.join(",") + ");");
        if (!oNewWindow) { alert("打开页面失败！\n\n提示：如果浏览器或其它软件拦截了新窗口，请设置它允许当前站点打开新窗口。"); }
    }
    return oNewWindow;
};

/* Prototype for Firefox */
if (is_moz) {
    HTMLElement.prototype.attachEvent = window.attachEvent = document.attachEvent = function (sEvent, fpNotify) {
        this.addEventListener(sEvent.replace(/^on/i, ''), fpNotify, false);
    };
    HTMLElement.prototype.detachEvent = window.detachEvent = document.detachEvent = function (sEvent, fpNotify) {
        this.removeEventListener(sEvent.replace(/^on/i, ''), fpNotify, false);
    };
    HTMLElement.prototype.__defineGetter__("innerText", function () {
        return this.textContent;
    });
    HTMLElement.prototype.__defineSetter__("innerText", function (sText) {
        this.textContent = sText;
    });
    HTMLElement.prototype.__defineSetter__('outerHTML', function (sHTML) {
        var r = this.ownerDocument.createRange();
        r.setStartBefore(this);
        var df = r.createContextualFragment(sHTML);
        this.parentNode.replaceChild(df, this);
        return sHTML;
    });
    HTMLElement.prototype.__defineGetter__('outerHTML', function () {
        var attr;
        var attrs = this.attributes;
        var str = '<' + this.tagName.toLowerCase();
        for (var i = 0; i < attrs.length; i++) {
            attr = attrs[i];
            if (attr.specified) str += ' ' + attr.name + '="' + attr.value + '"';
        }
        if (!this.canHaveChildren) return str + '>';
        return str + '>' + this.innerHTML + '</' + this.tagName.toLowerCase() + '>';
    });
    HTMLElement.prototype.__defineGetter__('canHaveChildren', function () {
        switch (this.tagName.toLowerCase()) {
            case 'area': case 'base': case 'basefont': case 'col': case 'frame': case 'hr': case 'img': case 'br': case 'input': case 'isindex': case 'link': case 'meta': case 'param':
                return false;
        }
        return true;
    });
    Event.prototype.__defineSetter__("returnValue", function (val) {
        if (val == false) this.preventDefault();
        return val;
    });
    Event.prototype.__defineGetter__("srcElement", function () {
        var o = this.target;
        while (o.nodeType == 3) o = o.parentNode;
        return o;
    });
    Event.prototype.__defineSetter__("cancelBubble", function (val) {
        if (val == true) this.stopPropagation();
        return val;
    });
    XMLDocument.prototype.loadXML = function (xmlString) {
        var childNodes = this.childNodes;
        for (var i = childNodes.length - 1; i >= 0; i--) {
            this.removeChild(childNodes[i]);
        }
        var dp = new DOMParser();
        var newDOM = dp.parseFromString(xmlString, "text/xml");
        var newElt = this.importNode(newDOM.documentElement, true);
        this.appendChild(newElt);
    };
    XMLDocument.prototype.__proto__.__defineGetter__("text", function () {
        return this.firstChild.textContent;
    });
    Element.prototype.__proto__.__defineGetter__("text", function () {
        return this.textContent;
    });
    Element.prototype.__proto__.__defineSetter__("text", function (sText) {
        this.textContent = sText;
    });
    (function () {
        var getter = function () {
            try {
                return new XMLSerializer().serializeToString(this);
            } catch (ex) {
                var d = document.createElement("div");
                d.appendChild(this.cloneNode(true));
                return d.innerHTML;
            }
        };
        XMLDocument.prototype.__proto__.__defineGetter__("xml", getter);
        Element.prototype.__proto__.__defineGetter__("xml", getter);
    })();
    XMLDocument.prototype.__proto__.__defineSetter__("xml", function (xmlString) { this.loadXML(xmlString); });
    XMLDocument.prototype.selectSingleNode = Element.prototype.selectSingleNode = function (sXPath) {
        var oEvaluator = new XPathEvaluator();
        var oResult = oEvaluator.evaluate(sXPath, this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
        if (oResult != null) {
            return oResult.singleNodeValue;
        }
        return null;
    };
    XMLDocument.prototype.selectNodes = Element.prototype.selectNodes = function (sXPath) {
        var oEvaluator = new XPathEvaluator();
        var oResult = oEvaluator.evaluate(sXPath, this, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
        var aNodes = new Array();
        if (oResult != null) {
            var oElement = oResult.iterateNext();
            while (oElement) {
                aNodes.push(oElement);
                oElement = oResult.iterateNext();
            }
        }
        return aNodes;
    };

    if (!window.clipboardData) {
        (function () {
            var sAlertMessage = "当前 FireFox 浏览器的复制和粘贴功能被浏览器拒绝或禁用！\n请允许浏览器进行这些操作，或者按以下方法开启功能：\n在浏览器地址栏输入“about:config”并回车，\n然后找到“signed.applets.codebase_principal_support”项并双击它，设置为“true”。";
            window.clipboardData = new Object();
            window.clipboardData.setData = function (sDataFormat, sData) {
                try {
                    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                } catch (e) {
                    alert(sAlertMessage);
                    return false;
                }
                var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
                if (!clip) return false;
                var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
                if (!trans) return false;
                trans.addDataFlavor('text/unicode');
                var str = new Object();
                var len = new Object();
                var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
                var copytext = sData;
                str.data = copytext;
                trans.setTransferData("text/unicode", str, copytext.length * 2);
                var clipid = Components.interfaces.nsIClipboard;
                if (!clip) return false;
                clip.setData(trans, null, clipid.kGlobalClipboard);
                return true;
            };
            window.clipboardData.getData = function (sDataFormat) {
                try {
                    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
                } catch (e) {
                    alert(sAlertMessage);
                    return null;
                }
                var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
                if (!clip) return null;
                var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
                if (!trans) return null;
                trans.addDataFlavor('text/unicode');
                clip.getData(trans, clip.kGlobalClipboard);
                var str = new Object();
                var len = new Object();
                try {
                    trans.getTransferData('text/unicode', str, len);
                } catch (e) {
                    return null;
                }
                if (str) {
                    if (Components.interfaces.nsISupportsWString) {
                        str = str.value.QueryInterface(Components.interfaces.nsISupportsWString);
                    } else if (Components.interfaces.nsISupportsString) {
                        str = str.value.QueryInterface(Components.interfaces.nsISupportsString);
                    } else {
                        str = null;
                    }
                }
                if (str) return str.data.substring(0, len.value / 2);
            };
        })();
    }

    if (!window.showModalDialog) {
        (function () {
            var getFeature = function (sFeatures, name) {
                var arr = null;
                var re = new RegExp("(?:;|^)\\s*" + name + "\\s*:\\s*([0-9A-Za-z]+)\\s*(?:;|$)");
                if ((arr = re.exec(sFeatures)) != null) return arr[1];
                return "";
            };
            var arrFeature1 = ["dialogHeight", "dialogLeft", "dialogTop", "dialogWidth", "resizable", "scroll", "status"];
            var arrFeature2 = ["height", "left", "top", "width", "resizable", "scrollbars", "status"];
            window.showModalDialog = function (sURL, vArguments, sFeatures) {
                var sNewFeatures = "";

                if (sFeatures) {
                    for (var i = 0, len = arrFeature1.length, sValue = ""; i < len; i++) {
                        sValue = getFeature(sFeatures, arrFeature1[i]);
                        if (sValue.length != 0) {
                            if (/^\d+/.test(sValue) == true) sValue = parseInt(sValue, 10).toString();
                            if (sNewFeatures.length != 0) sNewFeatures += ",";
                            sNewFeatures += arrFeature2[i] + "=" + sValue;
                        }
                    }
                }

                if (sNewFeatures.length != 0) sNewFeatures += ",";
                sNewFeatures += "modal=yes";

                window.openEx(sURL, undefined, sNewFeatures);
            };
        })();
    }

    if (parseFloat(is_moz) < 3.0) {
        (function () {
            var sCookieName = "check_ff_browser";
            if (CookieHelper.get(sCookieName) != "1") {
                CookieHelper.set(sCookieName, "1", null);
                var retVal = window.confirm("当前的 Firefox 浏览器版本过低，部分页面功能将会无法使用，请升级为 3.0 或以上版本的浏览器。\n\n点击“确定(OK)”打开最新 Firefox 的官方下载页面……");
                if (retVal == true) { window.openEx("http://en-us.www.mozilla.com/en-US/firefox/all.html", "_download_firefox"); }
            }
        })();
    }
}

/* Web Virtual Path */
window.$webroot = CookieHelper.get("WEBROOT");
if (!window.$webroot || window.$webroot == "/") window.$webroot = "";

/* UI Helper */
var UIHelper = {
    // 显示/隐藏 obj
    showHide: function (obj) {
        obj.style.display = (obj.style.display == "none") ? "" : "none";
    },

    // 让 objImg 的图片在 img1 和 img2 间切换

    changeImg: function (objImg, img1, img2) {
        objImg.src = (objImg.src.toLowerCase().indexOf(img1.toLowerCase()) >= 0) ? img2 : img1;
    },

    // 从 obj 开始向上查找满足 条件 condition 的元素, 最大查找深度为 deep.
    // 如 UIHelper.findUpper( oInput, 10, "obj.tagName == 'IMG'" ) 表示
    //   从 oInput 向上查找元素, 该元素的 tagName 是 IMG, 找到就返回, 最大查找深度为 10.
    //   即: 找 oInput 前面最近的图片.
    findUpper: function (obj, deep, condition) {
        while (obj && deep > 0) {
            if (eval(condition)) return obj;
            obj = obj.parentNode;
            deep--;
        }
        return null;
    },

    // 从 obj 开始向下查找满足条件 condition 的元素, 最大查找尝试为 deep.
    findLower: function (obj, deep, condition) {
        if (deep > 0 && eval(condition)) return obj;
        if (obj.hasChildNodes()) {
            deep--;
            for (var i = 0; i < obj.childNodes.length; i++) {
                var child = obj.childNodes[i];
                if (child.nodeType == 3) continue;
                var retObj = UIHelper.findLower(child, deep, condition);
                if (retObj) return retObj;
            }
        }
        return null;
    },

    // 从 obj 开始向下遍历元素, 当元素满足条件 condition 时, 将调用 callback(obj, callbackParam )
    //  遍历最大深度为 deep.
    walkthrough: function (obj, condition, deep, callback, callbackParam) {
        var sender = obj;
        var e = callbackParam;
        e.obj = obj;
        if (e.doreturn == true) return;
        if (deep > 0 && eval(condition)) {
            callback.call(this, sender, e);
        }
        if (obj.hasChildNodes()) {
            deep--;
            for (var i = 0; i < obj.childNodes.length; i++) {
                var child = obj.childNodes[i];
                if (child.nodeType == 3) continue;
                UIHelper.walkthrough(child, condition, deep, callback, e);
            }
        }
    }
};

/* 页面元素遍历器 */
var PageWolkthrougher = {
    walk: false,
    doWalk: function () {
        if (!PageWolkthrougher.walk) return;
        var e = {};
        UIHelper.walkthrough(document.body, "true", Number.MAX_VALUE, PageWolkthrougher.doWalk_callback, e);
        if (e.invodeObj && e.invodeObj["finish"]) e.invodeObj.finish();
    },
    doWalk_callback: function (sender, e) {
        var sWeb = e.obj.getAttribute("web");
        if (sWeb == null) return;
        var webs = sWeb.split(',');
        for (var i = 0, len = webs.length; i < len; i++) {
            var web = webs[i];
            var invodeObj = window["Web_" + web];
            if (!invodeObj) continue;
            if (!e[web] && invodeObj["start"]) invodeObj.start();
            e.invodeObj = invodeObj;
            e[web] = true;
            invodeObj.object = e.obj;
            invodeObj.invoke(e.obj, e);
        }
    }
};
window.attachEvent("onload", PageWolkthrougher.doWalk);

function getAbsoluteOffset(obj) {
    var left_offset = obj.offsetLeft;
    var top_offset = obj.offsetTop;
    while ((obj = obj.offsetParent) != null) {
        left_offset += obj.offsetLeft;
        top_offset += obj.offsetTop;
    }
    return { left: left_offset, top: top_offset };
}
/* master */
function masterAutoSize(evt) {
    var objHeader = $$("header");
    var objFooter = $$("footer");
    var objContent = $$("content");
    var objMainArea = $$("divMainArea");
    var objImg=$$("divImg");
    var objDescript=$$("divDeiscription");
    var objDoc = document.documentElement || document.body;
    var bResized = false;

    var isIESix = (is_ie && parseFloat(is_ie) < 7.0);

    var pageResize = function (e) {
        var newSize = 0;
        bResized = false;

        if (objContent) {
            newSize = objDoc.clientHeight - 14;
            if (objHeader) { newSize -= objHeader.offsetHeight; }
            if (objFooter) { newSize -= objFooter.offsetHeight; }
            if (isIESix) { newSize += 2; }   // IE6
            objContent.style.height = Math.max(newSize, 1) + "px";
            try
            {    
                if(objImg)
                {
                    objImg.style.height =objContent.style.height;
                    objImg.style.width =objDoc.clientWidth-236+"px";
                } 
                var objlist=objContent.childNodes[1].childNodes[4].childNodes[0];
                var objSearch   =$$("search");
                var objToolbar   =$$("toolbar"); 
                var objBottom   =$$("divBottom"); 
                if(objSearch)    
                {
                    newSize = newSize - objSearch.clientHeight-30;
                } 
                if(objToolbar)    
                {
                    newSize = newSize - 25;
                } 
                if(objBottom)    
                {
                    newSize = newSize - objBottom.clientHeight-30;
                }        
                newSize = newSize-50;           
                if (isIESix) { newSize += 2; }   // IE6
                objlist.style.height = Math.max(newSize, 1) + "px"; 
                objlist.style.margin="0"; 
                objlist.style.overflow="auto";                         
                objlist.style.position="inherit";                                                                                           
            }   
            catch(e)
            {} 
            // IE6
            if (isIESix) {
                newSize = objDoc.clientWidth - 10;  // -10 may is margin
                objContent.style.width = Math.max(newSize, 1) + "px";
            }

            bResized = true;            
        }

        if (objMainArea && (isIESix || is_opera)) {
            newSize = objDoc.clientWidth - getAbsoluteOffset(objMainArea).left - 8; // Opera
            if (isIESix) { newSize -= 2; } // IE6
            objMainArea.style.width = Math.max(newSize, 1) + "px";

            bResized = true;
        }
         
    };

    // Opera
    if (objMainArea && is_opera) { objMainArea.style.position = "absolute"; }

    pageResize(window.event || evt);

    if (bResized == true) {
        var oAttacher = window;
        //if (is_ie && objHeader) { oAttacher = objHeader; }
        oAttacher.attachEvent("onresize", pageResize);
    }
}

/* list */
function default_openEditor(pageName, paramObject, action, width, heght, boolscroll) {
    if (width == undefined)
        width = 600;
    if (heght == undefined)
        heght = 450;
    //alert(boolscroll);

    var queryString = "";
    if (paramObject) {
        var attrs = paramObject.attributes;
        for (var i = 0, len = attrs.length; i < len; i++) {
            var name = attrs[i].name || attrs[i].nodeName;
            var value = attrs[i].value || attrs[i].nodeValue;
            if (name.substring(0, 1) == "_") {
                if (queryString.length > 0) { queryString += "&"; }
                queryString += name.substring(1) + "=" + encodeURIComponent(value);
            }
        }
    }
    if (action != undefined && action != null) {
        if (queryString.length > 0) { queryString += "&"; }
        queryString += "cmd=" + action;
    }
    var sUrl = pageName;
    if (queryString.length > 0) {
        if (sUrl.indexOf("?") > -1) {
            sUrl += "&" + queryString;
        }
        else {
            sUrl += "?" + queryString;
        }
    }
    var parameters = "dialogwidth:" + width + "px;dialogheight:" + heght + "px;help:0;center:yes;resizable:0;toolbar=0;titlebar:0;status:0;scroll:0;help:0;dialogHide:0;edge:raised;";
    if (boolscroll) {
        var parameters = "dialogwidth:" + width + "px;dialogheight:" + heght + "px;help:0;center:yes;resizable:0;toolbar=0;titlebar:0;status:0;scroll:1;help:0;dialogHide:0;edge:raised;";
    }
    //var result = window.showModalDialog(sUrl, null, "dialogWidth=" + width + "px;dialogHeight=" + heght + "px");
    var result = window.showModalDialog(sUrl, null, parameters);

    if (result == "refresh") {
        window.location = window.location;
    }
    else if (result == "true" || result == "OK") {
        return true;
    }
    else if (result == "false" || result == null || result == undefined) {
        return false;
    }

    return result;
}

/* 使用此方法创建 XML Document 对象 */
function createXmlDocument() {
    var dom = null;
    if (!window.DOMParser && window.ActiveXObject) {    // IE
        var arrXmlDomTypes = ['MSXML2.DOMDocument.6.0', 'MSXML2.DOMDocument.3.0', 'Microsoft.XMLDOM'];
        for (var i = 0, len = arrXmlDomTypes.length; i < len; i++) {
            try { dom = new ActiveXObject(arrXmlDomTypes[i]); } catch (e) { continue; }
            if (dom) break;
        }
    } else if (document.implementation && document.implementation.createDocument) { // Firefox
        dom = document.implementation.createDocument("", "", null);
    }
    return dom;
}


function getElementEndWithId(endWithId) { 
    for (var i = 0; i < document.all.length; i++) {
        if (document.all[i].id.indexOf(endWithId) >= 0)
            return document.all[i];
    }
}


function reset()
{    
    var formObj = document.forms[formName];
    var formEl = formObj.elements;   
    for (var i=0; i<formEl.length; i++)     {         
    var element = formEl[i];         
    if (element.type == 'submit') { continue; }         
    if (element.type == 'reset') { continue; }         
    if (element.type == 'button') { continue; } 
    if (element.type == 'hidden') {
     if(element.name!='method' ) {element.value = '';}
    }
    if (element.type == 'text') { element.value = ''; }        
    if (element.type == 'textarea') { element.value = ''; }        
    if (element.type == 'checkbox') { element.checked = false; }         
    if (element.type == 'radio') { element.checked = false; }         
    if (element.type == 'select-multiple') { element.selectedIndex = 0; }         
    if (element.type == 'select-one') { element.selectedIndex = 0; }    
    }
}